import { FileTreeEntries, FileTreeEntry } from '@/typings'
import { isArray, joinPath } from '../common'

export type FileMap = { [filePath: string]: any }
/**
 * 将文件列表转换为树结构
 */
export function convertToFileTree(
  fileMap: { [filePath: string]: any } | string[]
): FileTreeEntries {
  if (isArray(fileMap)) {
    const fileList = fileMap as string[]
    fileMap = fileList.reduce<{ [key: string]: any }>((obj, v, i) => {
      obj[v] = i
      return obj
    }, {})
  }
  const result: FileTreeEntries = []
  if (!Object.keys(fileMap).length) return []

  for (const filepath in fileMap) {
    if (!filepath) continue
    let pathParts: string[] = []
    if (filepath === '/') pathParts.push('/')
    else {
      pathParts = filepath.split('/')
      if (pathParts.length > 0 && pathParts.at(0) === '') {
        pathParts[0] = '/'
      }
    }
    let currentLevel = result
    for (let i = 0; i < pathParts.length; ++i) {
      const pathPart = pathParts.at(i)!
      let currentItem = currentLevel.find((e) => e.name === pathPart)
      if (!currentItem) {
        currentItem = new FileTreeEntry({
          name: pathPart,
          key: joinPath(...pathParts.slice(0, i + 1)),
          data: {},
          children: [],
        })
        currentLevel.push(currentItem)
      }
      if (i === pathParts.length - 1) {
        currentItem.data = fileMap[filepath]
      }
      currentLevel = currentItem.children
    }
  }
  return result
}
